package com.fingard.dsp.bank.directbank.cmbunion02;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.SendBankRespose;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.directbank.cmbunion02.utils.SignatureUtil;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

public class CMBUnion02Statement extends CMBUnion02Base implements IStatement {
    public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();

        String[] tmpSenderUnderHeader = getSenderUnderStatement(p_reqQrySttm, retAts);
        String tmpSenderUnderTotalNum = retAts.totalNum;
        if (retAts.getWrittenRdCount() == 0) {
            if ("-1".equals(tmpSenderUnderHeader[0])) {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpSenderUnderHeader[1]);
            } else {
                retAts.writeRespCode("0");
                retAts.writeRespInfo("交易为空");
            }
        } else {
            retAts.isWritedTotalNum(String.valueOf(Integer.parseInt(tmpSenderUnderTotalNum)));
        }

        retAts.writeEnd();
        return retAts;
    }
    public String[] getSenderUnderStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
        String[] respHeader = new String[] { "", "" };

        String respCode = "";
        String respInfo = "";
        int totalNum = 0;
        retAts.totalNum = "0";

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_reqQrySttm.actNum, "");
            if (actItem == null) {
                respHeader[0] = "-1";
                respHeader[1] = "未找到账号[" + p_reqQrySttm.actNum + "]相应商户配置信息!";
                return respHeader;
            }
            Map<String, String> requestPublicParams = getCommonMap();
            Map<String, Object> order = new HashMap<String, Object>();
            order.put("merId", actItem.merchantId);
            order.put("billDate", p_reqQrySttm.busDate);
            WriteBankUrlLogLn("招商聚合扫码下单地址："+bankFront.serverURL+"/statementurl");
            ObjectMapper mapper = new ObjectMapper();
            requestPublicParams.put("biz_content", mapper.writeValueAsString(order));
            WriteBankLogLn("招商聚合加签前的报文内容：" + mapper.writeValueAsString(requestPublicParams));
            String signContent= SignatureUtil.getSignContent(requestPublicParams);
            String sign = SignatureUtil.rsaSign(signContent, actItem.ownKeyStorePath, "UTF-8");
            requestPublicParams.put("sign", sign);
            String[] tmpStrRet = sendToBank(sign,mapper.writeValueAsString(requestPublicParams),bankFront.serverURL+"/statementurl",actItem);
            if(tmpStrRet[0].length() == 0){
                JSONObject resultObj = JSONObject.parseObject(tmpStrRet[1]);
                if(resultObj.get("returnCode")!=null && "SUCCESS".equals(resultObj.get("returnCode"))){
                    JSONObject biz_content = JSONObject.parseObject(resultObj.getString("biz_content"));
                    if(resultObj.get("respCode")!=null && "SUCCESS".equals(resultObj.get("respCode"))){
                        WriteBankLogLn("对账单文件下载链接:"+biz_content.get("fileDownloadUrl"));
                        String filePath = createTempFileDirectory() + File.separator + p_reqQrySttm.actNum + "_" + p_reqQrySttm.busDate + ".xlsx";
                        WriteBankLogLn("对账单下载后保存到本地路径:" + filePath);
                        SendBankRespose retResp = smsGet(biz_content.get("fileDownloadUrl").toString(), filePath, actItem.billRequestType);
                        if (retResp.connState == "") {
                            String respStr = retResp.retMessage;
                            StringReader strReader = new StringReader(respStr);
                            BufferedReader tmpReader = new BufferedReader(strReader);
                            while (true) {
                                String eachline = tmpReader.readLine();
                                if (eachline == null) {
                                    break;
                                }
                                String deaNode[] = eachline.split(",");
                                if ("new".equalsIgnoreCase(actItem.billRequestType)) {
                                    RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
                                    tmpRetDetail.askNumber = deaNode[0];
                                    tmpRetDetail.bkSeq = deaNode[1];
                                    tmpRetDetail.fee = deaNode[15];
                                    tmpRetDetail.amount = deaNode[14];
                                    tmpRetDetail.busTime = deaNode[7]+deaNode[8].replace(":","");
                                    tmpRetDetail.oppAct = deaNode[12];
                                    tmpRetDetail.oppBank = deaNode[13];
                                    tmpRetDetail.transState = TransState.Success;

                                    if ("S".equalsIgnoreCase(p_reqQrySttm.statementType) && "消费".equalsIgnoreCase(deaNode[4])) {
                                        totalNum++;
                                        tmpRetDetail.cdFlag = "22";
                                        retAts.writeRetDetail(tmpRetDetail);
                                    } else if ("F".equalsIgnoreCase(p_reqQrySttm.statementType) && "退款".equalsIgnoreCase(deaNode[4])) {
                                        totalNum++;
                                        tmpRetDetail.cdFlag = "27";
                                        retAts.writeRetDetail(tmpRetDetail);
                                    } else {
                                        totalNum++;
                                        if ("消费".equalsIgnoreCase(deaNode[4])) {
                                            tmpRetDetail.cdFlag = "22";
                                        } else if ("退款".equalsIgnoreCase(deaNode[4])) {
                                            tmpRetDetail.cdFlag = "27";
                                        }
                                        retAts.writeRetDetail(tmpRetDetail);
                                    }
                                } else {
                                    if(deaNode[0].contains("交易")){
                                        continue;
                                    }
                                    if(deaNode[37].equals("S")){
                                        RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
                                        totalNum++;
                                        tmpRetDetail.amount = deaNode[15];
                                        tmpRetDetail.busTime = deaNode[1]+deaNode[2].replace(":","");
                                        tmpRetDetail.askNumber = deaNode[9];
                                        tmpRetDetail.bkSeq = deaNode[8];
                                        tmpRetDetail.fee = deaNode[16];
                                        tmpRetDetail.oppAct = deaNode[11];
                                        tmpRetDetail.memo = deaNode[38];
                                        tmpRetDetail.transState = TransState.Success;
                                        tmpRetDetail.cdFlag = "22";
                                        retAts.writeRetDetail(tmpRetDetail);
                                    }
                                }
                            }
                        }else {
                            respCode = "-1";
                            respInfo = retResp.retMessage;
                        }
                    }else {
                        respCode = "-1";
                        respInfo = resultObj.getString("respMsg");
                    }
                }else {
                    respCode = "-1";
                    respInfo = resultObj.getString("respMsg");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            respCode = "-1";
            respInfo = e.getMessage();
            WriteBankLogLn(e);
        }
        retAts.totalNum = String.valueOf(totalNum);
        respHeader[0] = respCode;
        respHeader[1] = respInfo;

        return respHeader;
    }
}
